package com.cyz.admin.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyz.admin.service.AdService;
import com.cyz.common.bean.Ad;
import com.cyz.common.dto.AdDto;
import com.cyz.common.enums.MyEnums;
import com.cyz.common.mapper.AdMapper;
import com.cyz.common.utils.BeanCopyUtil;
import com.cyz.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 管理端广告接口实现类
*/
@Service
@Transactional
public class AdServiceImpl extends ServiceImpl<AdMapper, Ad>
    implements AdService{

    @Autowired
    private AdMapper adMapper;
//    @Autowired
//    private AdService adService;

    @Override
    public R queryFreeAds() {

        //创建筛选条件
//        mybatis
//        mybatisplus
//        LambdaQueryWrapper<Ad> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//        //查询类型为免费的广告
//        lambdaQueryWrapper.eq(Ad::getType, MyEnums.FREE_AD_TYPE);
//        //根据更新时间排序
//        lambdaQueryWrapper.orderByDesc(Ad::getUpdateTime);
        //查询数据
//        List<Ad> list = list(lambdaQueryWrapper);
//        List<Ad> list = adService.list();

        //查询类型为免费的广告
        //根据更新时间排序
        List<Ad> list = adMapper.selectFreeAds(MyEnums.FREE_AD_TYPE);

        return R.success(list);
    }

    @Override
    public R deleteFreeAds(Integer[] ids) {
//        //删除数据
//        boolean flag = removeByIds(Arrays.asList(ids));

        //删除数据
        boolean flag = adMapper.removeByIds(ids);
        //错误判断
        if(!flag){
            return R.error(MyEnums.DELETE_FAIL);
        }
        return queryFreeAds();
    }


    @Override
    public R addFreeAds(AdDto adDto) {
        //转化dto
        Ad ad = BeanCopyUtil.copyBean(adDto, Ad.class);
        //设置类型
        ad.setType(MyEnums.FREE_AD_TYPE);
//        //保存数据
//        boolean flag = save(ad);
        //保存数据
        boolean flag = adMapper.addFreeAds(ad);
        //错误判断
        if(flag){
            return queryFreeAds();
        }
        return R.error(MyEnums.ADD_FAIL);
    }

    @Override
    public R updateFreeAd(AdDto adDto) {
        //转化dto
        Ad ad = BeanCopyUtil.copyBean(adDto, Ad.class);
//        //更新数据
//        boolean flag = updateById(ad);
        //更新数据
        boolean flag = adMapper.updateFreeAd(ad);

        //错误判断
        if(flag){
            return queryFreeAds();
        }
        return R.error(MyEnums.UPDATE_FAIL);
    }
}




